package com.shadow.demo.shiro.controller.sys;

import com.shadow.demo.data.shiro.entity.Permission;
import com.shadow.demo.data.shiro.entity.Role;
import com.shadow.demo.shiro.service.PermissionService;
import com.shadow.demo.shiro.service.RoleService;
import com.shadow.demo.shiro.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.annotation.Resource;
import java.lang.reflect.InvocationTargetException;
import java.util.*;
import java.util.stream.Collectors;

/**
 * Created by shadow
 * on 2022-6-29.
 * @ RequiresPermissions({"用户管理"})
 */
@Slf4j
@Controller
public class PageController {

    @Resource
    private PermissionService permissionService;
    @Resource
    private UserService userService;
    @Resource
    private RoleService roleService;

    /**
     * 用户主页面
     */
    @RequestMapping("/user/index")
    public String index() {
        return "index/index";
    }

    @GetMapping("/user/manage")
    public String userManage() {
        return "user/list";
    }

    @GetMapping("/user/list")
    public String userList() {
        return "user/list";
    }

    @GetMapping("/user/add")
    public String userAdd() {
        return "user/add";
    }

    @GetMapping("/user/edit/{id}")
    public String userEdit(@PathVariable("id") String id, final ModelMap model) {
        model.put("user", userService.getById(id));
        return "user/edit";
    }

    @GetMapping("/user/config/{id}")
    public String userConfig(@PathVariable("id") final String id, final ModelMap model) {
        List<Role> roleList = roleService.getAvailableList();
        List<Role> userRoleList = roleService.getRoleListByUserId(id);
        List<Object> collect = roleList.stream()
                .filter(x -> StringUtils.isNotEmpty(x.getCode()))
                .map(x -> {
                    Role a = userRoleList.stream()
                            .filter(y -> StringUtils.equals(x.getCode(), y.getCode()))
                            .findFirst()
                            .orElse(null);
                    try {
                        Map<String, String> map = BeanUtils.describe(x);
                        map.remove("class");
                        map.put("checked", (a != null) + StringUtils.EMPTY);
                        return map;
                    } catch (IllegalAccessException e) {
                        log.error("发生了错误 IllegalAccessException", e);
                    } catch (InvocationTargetException e) {
                        log.error("发生了错误 InvocationTargetException", e);
                    } catch (NoSuchMethodException e) {
                        log.error("发生了错误 NoSuchMethodException", e);
                    }
                    throw new IllegalArgumentException("error");
                })
                .collect(Collectors.toList());
        model.addAttribute("roleList", collect);
        model.addAttribute("id", id);
        return "user/config";
    }

    /**
     * 角色管理
     */
    @RequestMapping("/role/manage")
//    @RequiresPermissions({"角色管理"})
    public String roleManage() {
        return "role/list";
    }

    @GetMapping("/role/list")
    public String roleList() {
        return "role/list";
    }

    @GetMapping("/role/add")
    public String roleAdd() {
        return "role/add";
    }

    @GetMapping("/role/edit/{id}")
    public String roleEdit(@PathVariable("id") String id, final ModelMap model) {
        model.put("role", roleService.getById(id));
        return "role/edit";
    }

    @GetMapping("/role/config/{id}")
    public String roleConfig(@PathVariable("id") final String id, final ModelMap model) {
        List<Permission> allList = permissionService.getAllList();
        List<Permission> currentList = permissionService.getAllByRoleId(id);
        Set<String> currentSet = Optional.ofNullable(currentList)
                .orElse(Collections.emptyList())
                .stream()
                .map(Permission::getId)
                .filter(Objects::nonNull)
                .collect(Collectors.toSet());
        List<Object> collect = Optional.ofNullable(allList)
                .orElse(Collections.emptyList())
                .stream()
                .map(x -> {
                    try {
                        Map<String, String> map = BeanUtils.describe(x);
                        map.remove("class");
                        map.put("checked", String.valueOf(currentSet.contains(x.getId())));
                        return map;
                    } catch (IllegalAccessException e) {
                        log.error("发生了错误 IllegalAccessException", e);
                    } catch (InvocationTargetException e) {
                        log.error("发生了错误 InvocationTargetException", e);
                    } catch (NoSuchMethodException e) {
                        log.error("发生了错误 NoSuchMethodException", e);
                    }
                    throw new RuntimeException("error");
                })
                .collect(Collectors.toList());
        model.addAttribute("dataList", collect);
        model.addAttribute("id", id);
        return "role/config";
    }


    /**
     * 权限管理
     */
    @RequestMapping("/permission/manage")
//    @RequiresPermissions({"权限管理"})
    public String permissionManage() {
        return "permission/list";
    }

    @GetMapping("/permission/list")
    public String permissionList() {
        return "permission/list";
    }

    @GetMapping("/permission/add")
    public String permissionAdd() {
        return "permission/add";
    }

    @GetMapping("/permission/edit/{id}")
    public String permissionEdit(@PathVariable("id") String id, final ModelMap model) {
        model.put("permission", permissionService.getById(id));
        return "permission/edit";
    }

    /**
     * 密码修改
     */
    @RequestMapping("/changePassword")
    @RequiresPermissions({"密码修改"})
    public String changePassword() {
        return "changePassword";
    }

}
